<script lang="ts" setup>
import { ref } from 'vue'

import AdvancedTable from '@/components/sofastui/AdvancedTable/AdvancedTable.vue'
import AdvancedForm from '@/components/sofastui/AdvancedForm/AdvancedForm.vue'
import LTreeTable from '@/components/layout/LTreeTable.vue'
import MenuContainer from './components/MenuContainer.vue'

import { fields, config, formRules } from './constant'

const advancedFormRef = ref()
const advancedTableRef = ref()
const menuRef = ref()

const searchFormData = ref<{
  parentId?: number | null
}>({})

// 创建
const handelAdd = () => {
  console.log(searchFormData.value)
  advancedFormRef.value?.show('add', {
    parentId: searchFormData.value.parentId,
  })
}

// 行展开
const handelRowExpand = (data: { [key: string]: unknown }) => {
  advancedFormRef.value?.show('update', data)
}

// 刷新表格数据
const refreshData = () => {
  advancedTableRef.value!.refresh()
  menuRef.value!.refresh()
}

const handelItemClick = (key: string, keyPath: string) => {
  console.log('handelItemClick')
  console.log(key, keyPath)
  console.log(typeof key)
  searchFormData.value.parentId = Number(key)
}
</script>

<template>
  <LTreeTable>
    <template #tree>
      <MenuContainer ref="menuRef" @item-click="handelItemClick" />
    </template>

    <template #table>
      <AdvancedTable
        ref="advancedTableRef"
        :query="searchFormData"
        :fields="fields"
        :config="config"
        @add="handelAdd"
        @rowExpand="handelRowExpand"
      >
        <template #icon="scope">
          <i :class="scope.row.icon"></i>
        </template>
        <template #value="scope">
          <span>{{ scope.row.type === 2 ? scope.row.value : scope.row.path }}</span>
        </template>
        <template #path_perms="scope">
          <span>{{ scope.row.path || scope.row.perms }}</span>
        </template>
        <template #enabled="scope">
          <el-switch
            v-model="scope.row.enabled"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            style="--el-switch-on-color: #13ce66"
          />
        </template>
        <template #display="scope">
          <el-switch
            v-model="scope.row.display"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            style="--el-switch-on-color: #13ce66"
          />
        </template>
      </AdvancedTable>
    </template>
  </LTreeTable>
  <!-- 修改表单 -->
  <AdvancedForm ref="advancedFormRef" :config="config" :rule="formRules" @success="refreshData" />
</template>
